package petertel.pbx.conf.sip;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;

import petertel.pbx.conf.NameValuePair;
import petertel.pbx.connector.Executor;
import petertel.pbx.utils.ParserUtils;

public class SipConfBuilder {

	public static void main(String[] args) {
		Executor executor = new Executor("tel", "tel", "os4test");
		SipConf sipConf = new SipConf();
		SipConfBuilder.build(executor,sipConf);
		System.out.println(sipConf);
	}

	public static SipConf build(Executor executor,SipConf sipConf) {
		List<Device> devices = new ArrayList<Device>();
		sipConf.setDevices(devices);
		String content = ParserUtils.readFile(executor,
				"/etc/asterisk/sip.conf");
		BufferedReader breader = new BufferedReader(new StringReader(content));
		int lineno = 0;
		String currentSection = null;
		String currentTemplate = null;
		Device currentDevice = null;
		try {
			for (;;) {
				String line = breader.readLine();
				if (line == null) {
					break;
				}
				lineno++;
				if (ParserUtils.isSection(line)) {
					currentSection = ParserUtils.getSectionName(line);
					currentTemplate = ParserUtils.getSectionTemplate(line);
					currentDevice = new Device();
					currentDevice.setName(currentSection.trim());
					currentDevice.setTemplate(currentTemplate);
					currentDevice.setLineno(lineno);
					if (currentTemplate == null) {// 当前不处理模板，所以不添加到设备列表
						devices.add(currentDevice);
					}
					List<NameValuePair> properties = new ArrayList<NameValuePair>();
					currentDevice.setProperties(properties);
				} else if (currentSection == null) {
					;
				} else {
					if (ParserUtils.isPair(line)) {
						String name =ParserUtils.getPairName(line);
						String value = ParserUtils.getPairValue(line);
						NameValuePair pair = new NameValuePair();
						pair.setName(name);
						pair.setValue(value);
						pair.setLineno(lineno);
						currentDevice.addChild(-1,pair);
					} else {
						;
					}
				}
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return sipConf;
	}

}
